<template>
  <div class="min-h-screen bg-gradient-to-br from-sky-400 via-sky-500 to-blue-600">
    <!-- 顶部标题区 -->
    <div class="text-center py-12 text-white">
      <h1 class="text-4xl font-bold mb-4">AI营销方案生成系统</h1>
      <p class="text-lg opacity-90 mb-2">基于先进的AI和大数据智能分析技术，为您量身定制专业营销解决方案</p>
      <p class="text-base opacity-80">从需求分析到PPT生成，一站式营销方案制作平台</p>
    </div>

    <!-- 步骤指示器 -->
    <div class="flex justify-center items-center mb-12">
      <div class="flex items-center space-x-8">
        <div class="flex items-center">
          <div class="w-10 h-10 bg-white text-sky-600 rounded-full flex items-center justify-center font-bold text-lg">
            1
          </div>
          <span class="ml-3 text-white font-medium">填写需求</span>
        </div>
        <div class="w-8 h-0.5 bg-white opacity-50"></div>
        <div class="flex items-center">
          <div class="w-10 h-10 bg-white bg-opacity-30 text-white rounded-full flex items-center justify-center font-bold text-lg">
            2
          </div>
          <span class="ml-3 text-white font-medium opacity-70">方案生成</span>
        </div>
        <div class="w-8 h-0.5 bg-white opacity-30"></div>
        <div class="flex items-center">
          <div class="w-10 h-10 bg-white bg-opacity-30 text-white rounded-full flex items-center justify-center font-bold text-lg">
            3
          </div>
          <span class="ml-3 text-white font-medium opacity-70">确定方案</span>
        </div>
        <div class="w-8 h-0.5 bg-white opacity-30"></div>
        <div class="flex items-center">
          <div class="w-10 h-10 bg-white bg-opacity-30 text-white rounded-full flex items-center justify-center font-bold text-lg">
            4
          </div>
          <span class="ml-3 text-white font-medium opacity-70">生成PPT</span>
        </div>
      </div>
    </div>

    <div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 pb-12">

      <!-- 营销需求表单 -->
      <div class="bg-white rounded-2xl shadow-xl p-8">
        <div class="text-center mb-8">
          <h2 class="text-2xl font-bold text-gray-800 mb-2">营销需求表单</h2>
          <p class="text-gray-600">请详细填写以下信息，AI将基于您的需求生成专业的营销方案</p>
          <div class="text-sm text-red-500 mt-2">* 标记为必填项目</div>
        </div>
        
        <el-form 
          ref="formRef" 
          :model="formData" 
          :rules="formRules" 
          label-position="top"
          class="space-y-6"
        >
          <!-- 第一行：核心目标 + 目标受众 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="form-field-wrapper">
              <el-form-item prop="core_goal">
                <template #label>
                  <div class="flex items-center mb-2">
                    <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">1</span>
                    <span class="font-medium text-gray-700">核心目标 *</span>
                  </div>
                </template>
                <el-input 
                  v-model="formData.core_goal" 
                  placeholder="请输入核心目标"
                  class="custom-input"
                />
                <div class="text-xs text-gray-500 mt-1">如：品牌、营销、品牌推广、营销推广、产品推广等</div>
              </el-form-item>
            </div>
            
            <div class="form-field-wrapper">
              <el-form-item prop="target_audience">
                <template #label>
                  <div class="flex items-center mb-2">
                    <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">2</span>
                    <span class="font-medium text-gray-700">目标受众 *</span>
                  </div>
                </template>
                <el-input 
                  v-model="formData.target_audience" 
                  placeholder="请描述目标受众群体"
                  class="custom-input"
                />
                <div class="text-xs text-gray-500 mt-1">如：年轻白领、大学生、白领一族、企业高管、商务精英等</div>
              </el-form-item>
            </div>
          </div>
          
          <!-- 第二行：人均预算 + 关注要点 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="form-field-wrapper">
              <el-form-item prop="budget_per_person">
                <template #label>
                  <div class="flex items-center mb-2">
                    <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">3</span>
                    <span class="font-medium text-gray-700">人均预算 *</span>
                  </div>
                </template>
                <el-input 
                  v-model="formData.budget_per_person" 
                  placeholder="请输入人均预算"
                  class="custom-input"
                />
                <div class="text-xs text-gray-500 mt-1">如：约100元（100以下）、约500元（100-500元）、高端（500元以上）</div>
              </el-form-item>
            </div>
            
            <div class="form-field-wrapper">
              <el-form-item prop="focus_point">
                <template #label>
                  <div class="flex items-center mb-2">
                    <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">4</span>
                    <span class="font-medium text-gray-700">关注要点 *</span>
                  </div>
                </template>
                <el-input 
                  v-model="formData.focus_point" 
                  placeholder="请输入关注要点"
                  class="custom-input"
                />
                <div class="text-xs text-gray-500 mt-1">如：重大节假日、我们营销活动、新品发布活动、促销活动等</div>
              </el-form-item>
            </div>
          </div>
          
          <!-- 第三行：礼品类型偏好 + 具体产品 -->
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="form-field-wrapper">
              <el-form-item prop="gift_preference">
                <template #label>
                  <div class="flex items-center mb-2">
                    <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">5</span>
                    <span class="font-medium text-gray-700">礼品类型偏好</span>
                  </div>
                </template>
                <el-input 
                  v-model="formData.gift_preference" 
                  placeholder="请输入礼品类型偏好（选填）"
                  class="custom-input"
                />
                <div class="text-xs text-gray-500 mt-1">如：实用礼品、品牌礼品、科技</div>
              </el-form-item>
            </div>
            
            <div class="form-field-wrapper">
              <el-form-item prop="specific_product">
                <template #label>
                  <div class="flex items-center mb-2">
                    <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">6</span>
                    <span class="font-medium text-gray-700">具体产品</span>
                  </div>
                </template>
                <el-input 
                  v-model="formData.specific_product" 
                  placeholder="请输入具体产品（选填）"
                  class="custom-input"
                />
                <div class="text-xs text-gray-500 mt-1">可填写具体的产品或服务名称</div>
              </el-form-item>
            </div>
          </div>
          
          <!-- 第四行：客户痛点（全宽） -->
          <div class="form-field-wrapper">
            <el-form-item prop="customer_pain_point">
              <template #label>
                <div class="flex items-center mb-2">
                  <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">7</span>
                  <span class="font-medium text-gray-700">客户痛点 *</span>
                </div>
              </template>
              <el-input 
                v-model="formData.customer_pain_point" 
                type="textarea" 
                :rows="3"
                placeholder="请详细描述客户遇到的问题或痛点，如何解决这些问题，关注哪些方面等"
                class="custom-textarea"
              />
              <div class="text-xs text-gray-500 mt-1">详细描述客户在使用产品或服务过程中遇到的问题和困扰</div>
            </el-form-item>
          </div>
          
          <!-- 第五行：客户偏好（全宽） -->
          <div class="form-field-wrapper">
            <el-form-item prop="customer_preference">
              <template #label>
                <div class="flex items-center mb-2">
                  <span class="w-6 h-6 bg-blue-500 text-white rounded-full flex items-center justify-center text-sm font-bold mr-2">8</span>
                  <span class="font-medium text-gray-700">客户偏好 *</span>
                </div>
              </template>
              <el-input 
                v-model="formData.customer_preference" 
                type="textarea" 
                :rows="3"
                placeholder="请详细描述客户的偏好和需求，如何更好地满足客户需求，体验如何提升等"
                class="custom-textarea"
              />
              <div class="text-xs text-gray-500 mt-1">需要填写客户在产品选择和服务体验方面的偏好和期望</div>
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 操作按钮区 -->
      <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-center space-x-4">
          <el-button 
            size="large" 
            @click="resetForm"
          >
            重置表单
          </el-button>
          <el-button 
            type="primary" 
            size="large" 
            :loading="submitting"
            @click="submitRequirement"
          >
            {{ submitting ? '提交中...' : '生成营销方案' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { ChatDotRound, Document, Edit, Files, Loading } from '@element-plus/icons-vue'
import { useAppStore } from '@/stores'
import type { Template } from '@/api'

const router = useRouter()
const store = useAppStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()
const templates = ref<Template[]>([])
const selectedTemplate = ref<Template | null>(null)

// 表单数据
const formData = reactive({
  core_goal: '',
  target_audience: '',
  budget_per_person: '',
  focus_point: '',
  gift_preference: '',
  specific_product: '',
  customer_pain_point: '',
  customer_preference: ''
})

// 表单验证规则
const formRules: FormRules = {
  core_goal: [
    { required: true, message: '请输入核心目标', trigger: 'blur' }
  ],
  target_audience: [
    { required: true, message: '请描述目标受众', trigger: 'blur' }
  ],
  budget_per_person: [
    { required: true, message: '请输入人均预算', trigger: 'blur' }
  ],
  focus_point: [
    { required: true, message: '请输入关注要点', trigger: 'blur' }
  ],
  customer_pain_point: [
    { required: true, message: '请描述客户痛点', trigger: 'blur' }
  ],
  customer_preference: [
    { required: true, message: '请描述客户偏好', trigger: 'blur' }
  ]
}

// 加载模板
const loadTemplates = async () => {
  try {
    loading.value = true
    console.log('=== 开始加载模板 ===')
    
    await store.loadTemplates()
    templates.value = store.templates
    
    console.log('模板加载完成:')
    console.log('store.templates:', store.templates)
    console.log('templates.value:', templates.value)
    console.log('模板数量:', templates.value.length)
    
    // 自动选择第一个模板作为默认模板
    if (templates.value.length > 0) {
      selectedTemplate.value = templates.value[0]
      store.selectTemplate(templates.value[0])
      console.log('自动选择默认模板:')
      console.log('selectedTemplate.value:', selectedTemplate.value)
      console.log('默认模板ID:', selectedTemplate.value.id)
    } else {
      console.warn('没有可用的模板')
    }
  } catch (error) {
    console.error('加载模板失败:', error)
    ElMessage.error('加载模板失败，请刷新页面重试')
  } finally {
    loading.value = false
    console.log('=== 模板加载流程结束 ===')
  }
}

// 选择模板
const selectTemplate = (template: Template) => {
  selectedTemplate.value = template
  store.selectTemplate(template)
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    core_goal: '',
    target_audience: '',
    budget_per_person: '',
    focus_point: '',
    gift_preference: '',
    specific_product: '',
    customer_pain_point: '',
    customer_preference: ''
  })
}

// 提交需求
const submitRequirement = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    await formRef.value.validate()
    
    // 确认提交
    await ElMessageBox.confirm(
      '确认提交需求信息并生成营销方案？',
      '确认提交',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    submitting.value = true
    
    // 详细调试信息 - 检查模板状态
    console.log('=== 提交前详细检查 ===')
    console.log('templates.value:', templates.value)
    console.log('templates.value.length:', templates.value.length)
    console.log('selectedTemplate.value:', selectedTemplate.value)
    console.log('selectedTemplate.value?.id:', selectedTemplate.value?.id)
    
    // 确保有默认模板
    let templateId = selectedTemplate.value?.id
    if (!templateId && templates.value.length > 0) {
      templateId = templates.value[0].id
      selectedTemplate.value = templates.value[0]
      console.log('自动选择第一个模板:', templateId)
    }
    
    // 类型和值检查
    console.log('templateId 类型:', typeof templateId)
    console.log('templateId 值:', templateId)
    console.log('templateId 是否为空:', !templateId)
    console.log('templateId 是否为undefined:', templateId === undefined)
    console.log('templateId 是否为null:', templateId === null)
    console.log('templateId 是否为空字符串:', templateId === '')
    
    // 验证template_id必须存在且不为空
    if (!templateId || templateId === '' || templateId === null || templateId === undefined) {
      console.error('模板ID验证失败:', {
        templateId,
        selectedTemplate: selectedTemplate.value,
        templates: templates.value
      })
      ElMessage.error('模板ID缺失，请刷新页面重试')
      return
    }
    
    // 提交需求数据
    const requirementData = {
      template_id: templateId,
      core_goal: formData.core_goal,
      target_audience: formData.target_audience,
      budget_per_person: formData.budget_per_person,
      focus_point: formData.focus_point,
      customer_preference: formData.customer_preference,
      customer_pain_point: formData.customer_pain_point,
      gift_preference: formData.gift_preference,
      specific_product: formData.specific_product
    }
    
    console.log('=== 最终提交数据 ===')
    console.log('完整数据对象:', requirementData)
    console.log('template_id字段:', requirementData.template_id)
    console.log('JSON字符串:', JSON.stringify(requirementData, null, 2))
    
    const response = await store.submitRequirement(requirementData)
    
    console.log('=== API响应数据 ===')
    console.log('完整响应:', response)
    console.log('响应数据字段:', response.data)
    console.log('需求ID:', response.data?.requirement_id)
    
    // 从响应数据中正确获取requirement_id
    const requirementId = response.data?.requirement_id || response.requirement_id
    
    if (!requirementId) {
      console.error('未能获取到需求ID:', response)
      ElMessage.error('提交成功但未获取到需求ID，请重试')
      return
    }
    
    ElMessage.success('需求提交成功！正在跳转到AI对话页面...')
    
    // 跳转到对话页面
    setTimeout(() => {
      router.push({
        name: 'chat',
        query: {
          requirement_id: requirementId
        }
      })
    }, 1500)
    
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('提交需求失败:', error)
      ElMessage.error(error.message || '提交失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 组件挂载时加载模板
onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.requirement-form {
  min-height: 100vh;
  background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
}

.form-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.step-indicator {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.step-item {
  transition: all 0.3s ease;
}

.step-item.active {
  transform: scale(1.05);
}

.step-number {
  transition: all 0.3s ease;
}

.step-item.active .step-number {
  background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
  box-shadow: 0 4px 15px rgba(14, 165, 233, 0.4);
}

.step-item.completed .step-number {
  background: #10b981;
}

.step-line {
  background: linear-gradient(90deg, #e5e7eb 0%, #d1d5db 100%);
}

.step-item.completed .step-line {
  background: linear-gradient(90deg, #10b981 0%, #059669 100%);
}

.form-title {
  background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.form-field-wrapper {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  border: 1px solid rgba(14, 165, 233, 0.1);
}

.form-field-wrapper:hover {
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 8px 25px rgba(14, 165, 233, 0.15);
  transform: translateY(-2px);
}

.custom-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e1e5e9;
  transition: all 0.3s ease;
}

.custom-input :deep(.el-input__wrapper:hover) {
  border-color: #0ea5e9;
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.1);
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  border-color: #0ea5e9;
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.2);
}

.custom-textarea :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid #e1e5e9;
  transition: all 0.3s ease;
}

.custom-textarea :deep(.el-textarea__inner:hover) {
  border-color: #0ea5e9;
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.1);
}

.custom-textarea :deep(.el-textarea__inner:focus) {
  border-color: #0ea5e9;
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.2);
}

.action-buttons {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.submit-btn {
  background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
  border: none;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(14, 165, 233, 0.3);
}

.reset-btn {
  background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
  color: #374151;
  border: none;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 24px;
}

.el-checkbox-group .el-checkbox {
  margin-right: 20px;
  margin-bottom: 10px;
}

.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>